"""
Case Type   : datakit安装
Case Name   : 【实例管理】使用模板上传实例
Create At   : 2025/5/20
Owner       : @lonely-dance
Description :
    1.下载模板
    2.修改模板文件
    3.上传非csv文件
    4.上传csv文件，但内容与模板不匹配
    5.上传csv模板文件
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.合理报错
    4.合理报错
    5.成功
    6.成功
History     :
"""

import os
import re
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.datakit_api.CommonApi import CommonApi
from testcase.utils.CommonDatakit import CommonDatakit


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.pri_node = Node('PrimaryDbUser')
        self.pri_root_node = Node('PrimaryRoot')
        self.mysql_node = Node('mysql5')
        self.datakit_node = Node('Datakit_Root')
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)
        self.com_datakit = CommonDatakit(self.token)
        self.cluster_name = re.search(r'Case\d+', os.path.basename(__file__)).group()
        self.url = f"jdbc:opengauss://{self.pri_node.db_host}:{self.pri_node.db_port}/{self.pri_node.db_name}"

    def test_base_ops(self):
        text = '----step1：下载实例模板 expect:成功----'
        self.log.info(text)
        response = self.com_api.get_jdbcDbCluster_downloadTemplate()
        self.log.info(response.text)
        txt = '\"集群名称（自定义一个集群名，集群名相同则认为是同一个集群）\",\"连接URL（JDBC的URL信息，例如 jdbc:opengauss://IP:PORT/databasename）\",\"用户名（数据库连接用户名）\",\"密码（数据库用户名对应的密码）\"'
        self.assertIn(txt, response.text, '执行失败' + text)

        text = '----step2:修改模板文件 expect:成功----'
        self.log.info(text)
        cmd = f"""cd {macro.DB_MY_MYPATH}; 
        echo '{txt}\n\\"{self.cluster_name}\\",\\"{self.url}\\", \\"{self.pri_node.db_user}\\", \\"{self.pri_node.db_password}\\"' > jdbc-template.csv;"""
        self.log.info(cmd)
        res = self.pri_root_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '执行失败' + text)

        text = '----step3:上传csv文件，但内容与模板不匹配 expect：合理报错----'
        self.log.info(text)
        cmd = f"""cd {macro.DB_MY_MYPATH}; echo "{response.text.splitlines()[0]}\n{self.url},{self.pri_node.db_user}" > jdbc-template-error.csv; """
        self.log.info(cmd)
        res = self.pri_root_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '执行失败' + text)
        path = os.path.join(macro.DB_MY_MYPATH, "jdbc-template-error.csv")
        response = self.com_api.post_jdbcDbCluster_importAnalysis(path, node_name='PrimaryDbUser')
        self.log.info(response.json())
        self.assertEqual('The content of the file is malformed : The data in row 2 is wrong',
                         response.json()['msg'], '执行失败' + text)

        text = '----step4:上传非csv文件 expect:合理报错----'
        self.log.info(text)
        cmd = f"cd {macro.DB_MY_MYPATH};cp jdbc-template-error.csv jdbc-template-error.text;"
        self.log.info(cmd)
        res = self.pri_root_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '执行失败' + text)
        path = os.path.join(macro.DB_MY_MYPATH, "jdbc-template-error.text")
        response = self.com_api.post_jdbcDbCluster_importAnalysis(path, node_name='PrimaryDbUser')
        self.log.info(response.json())
        self.assertIn('The content of the file is malformed',
                      response.json()['msg'], '执行失败' + text)

        text = '----step5:上传csv模板文件 expect:成功----'
        self.log.info(text)
        path = os.path.join(macro.DB_MY_MYPATH, "jdbc-template.csv")
        response = self.com_api.post_jdbcDbCluster_importAnalysis(path, node_name='PrimaryDbUser')
        self.log.info(response.json())
        self.assertEqual(1, response.json()['data']['succNum'], '执行失败' + text)

    def tearDown(self):
        self.log.info('----step6:清理环境 expect:成功----')
        cmd = f'cd {macro.DB_MY_MYPATH};rm -rf jdbc-template*'
        res = self.pri_root_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual('', res, '执行失败')

        self.com_datakit.delete_db()
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
